package validate

import (
	"reflect"
	"strings"

	"project/study-go/logger"

	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/validator/v10"
)

var (
	Validator *validator.Validate
)

func init() {
	var (
		ok bool
	)
	Validator, ok = binding.Validator.Engine().(*validator.Validate)
	if !ok {
		logger.RoutineLogger.Fatal("init validator.validator error")
	}
	RegisterValidation()
	InitTranslate()
	RegisterTranslation()
	Validator.RegisterTagNameFunc(GetFieldNameByJsonTag)
}

//RegisterValidation 注册自定义校验
func RegisterValidation() {
	new(UserVaildator).RegisterValidation()
}

//RegisterTranslation 注册校验的翻译
func RegisterTranslation() {
	new(UserVaildator).RegisterTranslation()
}

//GetFieldNameByJsonTag 不返回结构体字段名而返回结构体字段json标签的名字
func GetFieldNameByJsonTag(field reflect.StructField) string {
	name := strings.SplitN(field.Tag.Get("json"), ",", 2)[0]
	if name == "-" {
		return ""
	}
	return name
}
